const express = require('express');//引入express
const router = express.Router();//引入express路由
const DB = require('../db/db');//引入数据库
let num = 1;
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/**
 * 获取首页信息
 */
router.get('/api/homecasual', (req, res) => {

      const data = require('../data/homecasual');
      res.json(data)
	  
});
/**
 * 获取搜索分类列表
 */
router.get('/api/searchgoods', (req, res) => {
	console.log('请求参数',req.url)
        const data = require('../data/search');
        res.json(data)
});
/**
 * 获取搜索商品列表
 */
router.post('/api/recommend',async (req, res)=>{
	//mysql数据查询
	let params = req.query || req.params;
	let sort = req.body
	console.log('参数2',sort)
	if(sort.sort == 'defult') sort.sort = 'undefined'; 
	if(sort.sort && sort.sort != 'undefined') sort.keyword = '';
	console.log('参数3',sort.keyword)

	let sql = 'SELECT * FROM recommend';

	let content = [];
	let isMore = false;//是否有多个查询参数
	//搜索关键词
	if(params.keyword && sort.sort == 'undefined'){
			console.log('进入1',sort)
		// 模糊查询两种方法直接在SQL语句后加 mysql.escape("%"+req.body.name+"%")
		// sql += " WHERE product_name LIKE "+mysql.escape("%"+req.body.name+"%")
		sql += " WHERE name LIKE ?";
		content.push( "%"+params.keyword+"%" );
		isMore = true;
	}
	if(sort.keyword && sort.sort == 'undefined'){
		console.log('进入2',sort)
		sql += " WHERE name LIKE ?";
		content.push( "%"+sort.keyword+"%" );
		isMore = true;
	}
	//排序
	if(!!sort.sort && sort.sort !== 'undefined' && num == 1){
		console.log('进入')
		if(sort.sort == 'price') num += 1;
		sql += " ORDER BY " + sort.sort + " DESC"
		console.log(sql)
	}else if(!!sort.sort && num == 2){
		sql += " ORDER BY " + sort.sort + " ASC"
		num -= 1;
	}
	if(params.age){
		if(isMore){//true代表有多个参数
			sql += "and age like ?";//and是两个条件都必须满足，or是或的关系
		}else{
			sql += " WHERE age LIKE ?";
		}
		content.push( "%"+params.age+"%" );
	}
	//分页
	if(params.page || params.page_size){//开启分页
		let current = params.page;//当前页码
		let pageSize = params.page_size;//一页展示多少条数据
		sql += " limit ?,?";
		content.push((current-1)*pageSize,parseInt(pageSize));
	}
	let results = await DB.query(sql,content);
	res.json(results)
	//本地数据json查询
    // setTimeout(function () {
    //     const data = require('../data/recommend');
    //     res.json(data)
    // }, 10);
});
/**
 * 获取搜索分类列表
 */
router.get('/api/sendgoods',async (req, res) => {
	//mysql数据查询
	let params = req.query || req.params;
	console.log("商品详情",params)
	let content = [];
	let sql = 'SELECT * FROM goods_list WHERE goodsId = ' + params.goodsId || 1;
	console.log(sql)
	let results = await DB.query(sql,content);
	console.log(results)
	res.json(results)
});
/**
 * 添加商品到购物车
 */
router.post('/api/add_shop_cart',async (req, res) => {
	
	// 2. 获取客户端传过来的商品信息
	let {goodsId,name,arr,img,price,num} = JSON.parse(req.body.data);
	console.log(goodsId,name,arr,img,price,num)
	let content = [];
	// 3. 查询数据
	let sql = "SELECT * FROM uni_cart WHERE goodsId = '" + goodsId + "' LIMIT 1";
	let results = await DB.query(sql,content);
	// console.log('加入购物车数据1',results);
	if(results){
		// 过滤RowDataPacket
		results = JSON.parse(JSON.stringify(results));
		if (results[0] && !!results) { // 3.1 商品已经存在

			let number = results[0].num + num;
			// 3.1.1 更新商品数量
			let sql = "UPDATE uni_cart SET num = " + number + " WHERE goodsId = '" + goodsId + "'";
			let data = await DB.query(sql,content);

			if(data){
				res.json({success_code: 200, message: '加入购物车成功!'});
			}else{
				res.json({err_code: 0, message: '加入购物车失败!'});
			}

		} else { // 3.2 商品不存在
			// 3.2.1 插入商品
			let sql = "INSERT INTO uni_cart(goodsId, name, arr, img, price, num) VALUES (?, ?, ?, ?, ?, ?)";
			content = [goodsId, name, arr, JSON.stringify(img), price, num];
			let results = await DB.query(sql,content);
			if(results){
				res.json({success_code: 200, message: '加入购物车成功!'});
			}else{
				res.json({err_code: 0, message: '加入购物车失败!'});
			}
		}
	}

});
/**
 * 修改购物车数据
 */
router.post('/api/update_shop_cart',async (req, res) => {
	// 2. 获取客户端传过来的商品信息
	let {goodsId,name,arr,img,price,num} = JSON.parse(req.body.data);
	console.log(goodsId,name,arr,img,price,num)
	let content = [];

	// 3.1.1 更新商品数量
	let sql = "UPDATE uni_cart SET " + "num = '" + num + "'" + "," + "arr = '" + arr + "'" + " WHERE goodsId = '" + goodsId + "'";
	let results = await DB.query(sql,content);
			if(results){
				res.json({success_code: 200, message: '更新购物车成功'});
			}else{
				res.json({err_code: 0, message: '更新购物车失败!'});
			}
})
/**
 * 删除购物车数据
 */
router.post('/api/deleteCartsGoods',async (req, res) => {

	let data = req.body.data
	let content = [];
	let sql = "";
	// 1.1 数据库查询的语句
	if(data.length === 1) sql = "DELETE FROM uni_cart WHERE goodsId = " + data
	else sql = "DELETE FROM uni_cart WHERE goodsId in " + "(" + data + ")"

	let results = await DB.query(sql,content);
	if(results){
		res.json({success_code: 200, message: '删除购物车成功'});
	}else{
		res.json({err_code: 0, message: '删除购物车失败!'});
	}
})
/**
 * 获取购物车数据
 */
router.get('/api/getCartsGoods',async (req, res) => {
	// 1.1 数据库查询的语句
	let content = [];
	let sql = "SELECT * FROM uni_cart";
	let results = await DB.query(sql,content);
	console.log(results)
	res.json(results)
})

module.exports = router;
